package viz.view.mediators
{
	import flash.system.ApplicationDomain;
	
	import mx.events.ModuleEvent;
	
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.mediator.Mediator;

	public class FSMModuleMediator extends Mediator
	{
		public static const NAME:String = "FSMModuleMediator";
		public static const LOAD_MODULE:String = "fsmviz/module/load";
		public static const LOAD_MODULE_READY:String = "fsmviz/module/ready";

		public function FSMModuleMediator(viewComponent:Object=null)
		{
			super(NAME, viewComponent);
			
		}
		
		public function get preferences():XML{
			return new XML(view.data.prefs);
		}
		
		public function get pivot():XML{
			return new XML(view.data.pivot);
		}
		
		public function destroyData():void{
			view.data = null;
		}
		
		override public function onRegister():void{
			initiateView();
		}
		override public function listNotificationInterests():Array{
			return [ LOAD_MODULE ];
		}
		
		override public function handleNotification(note:INotification):void{
			switch(note.getName()){
				case LOAD_MODULE:
					loadModule(note.getType());
					break;
			}
		}
		
		private function loadModule( url:String ):void{
			view.loader.applicationDomain = ApplicationDomain.currentDomain
			view.loader.url = url;
			view.loader.loadModule();
			view.loader.addEventListener(ModuleEvent.READY, onModuleReady);
			view.loader.addEventListener(ModuleEvent.ERROR, onModuleError);
		}			
		
		protected function initiateView():void{
			createChildMediators();
		}

		private function createChildMediators():void{
			facade.registerMediator( new KeyStrokeMediator( view.stage ));
			facade.registerMediator( new EditMediator(view.editBox) );
			//
		}
		
		private function createVizMediator():void{
			facade.registerMediator( new FlareVizMediator( view.loader.child ));
		}
		
		private function onModuleReady(event:ModuleEvent):void{
			createVizMediator()
			sendModuleReadyNote();
		}
		private function onModuleError(event:ModuleEvent):void{
			//sendModuleReadyNote();
		}
		
		private function sendModuleReadyNote():void{
			sendNotification(LOAD_MODULE_READY);
		}
		
		private function get view():FSMViz{
			return FSMViz( viewComponent );
		}
		
	}
}